package pl.smath.gui;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.List;
import java.util.prefs.BackingStoreException;

import javax.swing.JPanel;

import pl.smath.expression.MultiTerm;
import pl.smath.expression.NumberTerm;
import pl.smath.expression.SumTerm;
import pl.smath.expression.SymbolTerm;
import pl.smath.expression.Term;
import pl.smath.parser.ExpressionParser;

public class TreeGraph extends JPanel {
	
	private int CIRCLE_SIZE = 27;
	private int X_DISTANCE = 30;
	private int Y_DISTANCE = 70;
	
	private String expression; 
	private Term term;
	private Graphics2D g2d;
	private Font font = new Font("Arial", Font.PLAIN, 17);
	
	public TreeGraph(){
		setBackground(Color.white);
	}
	
	@Override public void paintComponent(Graphics g) {
        super.paintComponent(g);
        
        g2d = (Graphics2D)g;
        
       if (term != null)
    	   drawTerms(term, new Point(550, 30), 0);
	}
	
	
	public void draw(String expression){
		this.expression = expression;
		
		ExpressionParser parser = new ExpressionParser();
		
		term = parser.parseText( expression );
		repaint();
	}
	
	private void drawTerm(Term term, Point position){
		
		String text = term.getText();
		
		if (term instanceof NumberTerm ){
			if (((NumberTerm)term).isNegative())
				text = "-" + text;
			g2d.setColor(Color.gray);
		}
		if (term instanceof SumTerm ){
			g2d.setColor(Color.black);
		}
		else
			g2d.setColor(Color.black);
		g2d.fillOval(position.x, position.y, CIRCLE_SIZE, CIRCLE_SIZE);
		g2d.setColor(Color.black);
		g2d.drawOval(position.x, position.y, CIRCLE_SIZE, CIRCLE_SIZE);
		g2d.setColor(Color.white);
		g2d.setFont(font);
		g2d.drawString(text, position.x + 9, position.y + 19);
	}
	
	private void drawTerms(Term term, Point position, int level){
		
		int w = X_DISTANCE;
		if (level == 4) w = X_DISTANCE;
		else if (level == 3) w = 2*X_DISTANCE;
		else if (level == 2) w = 4*X_DISTANCE;
		else if (level == 1) w = 8*X_DISTANCE;
		else w = 16*X_DISTANCE;
		
		
		List<Term> list = null; 
		Point p = new Point(position);
		
		if (term instanceof SumTerm ){
			SumTerm sum = (SumTerm)term;
			list = sum.getTermsList();
			p.y += Y_DISTANCE;
			p.x -= (((list.size()-1) * w)) /2;
		}
		else if (term instanceof SymbolTerm ){
		}
		else if (term instanceof NumberTerm ){
		}
		else if (term instanceof MultiTerm ){
			MultiTerm multi = (MultiTerm)term;
			list = multi.getTermsList();
			p.y += Y_DISTANCE;
			p.x -= (((list.size()-1) * w)) /2;
		}
		if (list != null){
			for(Term t: list){
				
				g2d.setColor(Color.black);
				g2d.drawLine(position.x+CIRCLE_SIZE/2, position.y+CIRCLE_SIZE/2, p.x+CIRCLE_SIZE/2, p.y+CIRCLE_SIZE/2);
				
				drawTerms(t, p, level+1);
				p.x += w;
			}
		}
		
		if (term != null)
			drawTerm(term, position);
	}

}
